package delegate

import (
	"fmt"
	"reflect"
)

type tMsgDispatchDelegate struct {
	mSubHandlers map[string]IMsgHandler
}

func (me *tMsgDispatchDelegate) Register(cls string, handler IMsgHandler) {
	me.mSubHandlers[cls] = handler
}

func newMsgDispatchDelegate() IMsgHandler {
	it := &tMsgDispatchDelegate{
		mSubHandlers: make(map[string]IMsgHandler, 16),
	}

	it.Register("EchoMsg", newEchoMsgHandler())
	it.Register("TimeMsg", newTimeMsgHandler())

	return it
}


func (me *tMsgDispatchDelegate) Handle(request IMsg) IMsg {
	if request == nil {
		return nil
	}

	handler, ok := me.mSubHandlers[request.Class()]
	if !ok {
		fmt.Printf("tMsgDispatchDelegate.Handle, handler not found: id=%v, cls=%v\n", request.ID(), request.Class())
		return nil
	}

	fmt.Printf("tMsgDispatchDelegate.Handle, handler=%v, id=%v, cls=%v\n", reflect.TypeOf(handler).String(), request.ID(), request.Class())
	return handler.Handle(request)
}

var GlobalMsgDispatcher = newMsgDispatchDelegate()